package com.kantboot.project.file.controller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.kantboot.project.file.entity.CesFileOss;
import com.kantboot.project.file.entity.CesFileParent;
import com.kantboot.project.file.entity.CesFileStore;
import com.kantboot.project.file.repository.CesFileParentRepository;
import com.kantboot.project.file.repository.CesFileStoreRepository;
import com.kantboot.project.util.common.util.RestResult;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    CesFileParentRepository cesFileParentRepository;

    @Resource
    CesFileStoreRepository cesFileStoreRepository;


    @PostMapping("/upload/{bodyName}/{bodyField}")
    public RestResult<String> upload(
            @RequestParam("file") MultipartFile file,
            @PathVariable("bodyName") String bodyName,
            @PathVariable("bodyField") String bodyField,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "content", required = false) String content
    ) {
        CesFileParent byBodyNameAndBodyField
                = cesFileParentRepository.findByBodyNameAndBodyField(bodyName, bodyField);

        String objectName = fileName(file);

        if (byBodyNameAndBodyField.getStorageType().equals("path")) {
            String fileName = byBodyNameAndBodyField.getFilePath().getPath() + "/" + objectName;
            System.out.println("fileName = " + fileName);
            String substring = fileName.substring(0, fileName.lastIndexOf("/"));
            File file1 = new File(substring);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            try {
                file.transferTo(new File(fileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            CesFileStore cesFileStore = new CesFileStore();
            cesFileStore.setFilePathId(byBodyNameAndBodyField.getFilePathId());
            cesFileStore.setPath(fileName);
            cesFileStore.setStorageType(byBodyNameAndBodyField.getStorageType());
            cesFileStore.setFileParentId(byBodyNameAndBodyField.getId());

            cesFileStoreRepository.save(cesFileStore);
            return RestResult.success("上传成功", "上传成功");
        }

        if (byBodyNameAndBodyField.getStorageType().equals("oss")) {
            CesFileOss fileOss = byBodyNameAndBodyField.getFileOss();
            // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
            String endpoint = fileOss.getEndpoint();

            //LTAI78XQAZq2s5Rv
            //qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            String accessKeyId = fileOss.getAccessKeyId();
            String accessKeySecret = fileOss.getAccessKeySecret();
            // 填写Bucket名称，例如examplebucket。
            String bucketName = fileOss.getBucketName();

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            try {
                InputStream inputStream = file.getInputStream();
                // 创建PutObject请求。
                ossClient.putObject(bucketName, objectName, inputStream);
            } catch (Exception oe) {

            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
            CesFileStore cesFileStore = new CesFileStore();
            cesFileStore.setFileOssId(byBodyNameAndBodyField.getFileOssId());
            cesFileStore.setPath(objectName);
            cesFileStore.setStorageType(byBodyNameAndBodyField.getStorageType());
            cesFileStore.setFileParentId(byBodyNameAndBodyField.getId());
            cesFileStoreRepository.save(cesFileStore);
            return RestResult.success("上传成功", "上传成功");
        }

        return RestResult.success("上传错误", "上传错误");

    }
    @Resource
    private OSS oss;
    /**
     * 获取访问路径
     */
    @SneakyThrows
    @RequestMapping("/get_visit_url")
    public RestResult<String> getViewUrl(@RequestParam("id") Long id){
        CesFileStore cesFileStore = cesFileStoreRepository.findById(id).get();
        if(cesFileStore.getFileParent().getUseTemporaryUrl()){
            return RestResult.error("获取失败");
        }
        if(cesFileStore.getStorageType().equals("path")){
            return RestResult.success(cesFileStore.getFilePath().getHost()+"/kantboot-file/file/path_visit/"+id,"获取成功");
        }
        if(cesFileStore.getStorageType().equals("oss")){
            Date expiration = new Date(new Date().getTime() + 1000 * 30);

            URL url = oss
                    .generatePresignedUrl(cesFileStore.getFileOss().getBucketName(),
                            cesFileStore.getPath(),expiration);
            return RestResult.success(url.toString(),"获取成功");
        }
        return RestResult.error("获取失败");
    }

    /**
     * 查看在本地存储的文件
     */
    @SneakyThrows
    @RequestMapping("/path_visit/{id}")
    public void pathView(@PathVariable("id") Long id,HttpServletResponse response){
//        response.setContentType("application/x-download");
        response.setCharacterEncoding("UTF-8");
        CesFileStore cesFileStore = cesFileStoreRepository.findById(id).get();
        if(cesFileStore.getFileParent().getUseTemporaryUrl()){
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(RestResult.error("请获取临时URL访问")));
            writer.flush();
            writer.close();
        }
//        response.setHeader("Content-Disposition", "attachment;filename=1.png");
        String realPath=cesFileStoreRepository.findById(id).get().getPath();

        String substring = realPath.substring(realPath.lastIndexOf("/"));
        response.setHeader("Content-Disposition", "filename="+UUID.randomUUID().toString()+"."+substring);
        FileInputStream inputStream = new FileInputStream(new File(realPath));
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();

    }

    //获取上传到oss后的名字
    private static String fileName(MultipartFile myfile) {

        Calendar calendar = Calendar.getInstance();
        String name = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/" +
                calendar.get(Calendar.DATE) + "/" + UUID.randomUUID().toString().replace("-", "") +
                myfile.getOriginalFilename();

        return name;
    }

}
